<template>
  <div class="login-page">
    <!-- 背景装饰元素 -->
    <div class="bg-decoration">
      <div class="wave"></div>
      <div class="wave"></div>
      <div class="wave"></div>
    </div>

    <div class="login-container">
      <!-- 左侧品牌展示区 -->
      <div class="login-banner">
        <div class="banner-content">
          <div class="brand-logo">
            <el-icon class="logo-icon"><ShoppingCart /></el-icon>
            <h1 class="brand-name">MallManager</h1>
          </div>
          <h2 class="banner-title">乐淘商城管理系统</h2>
          <p class="banner-desc">高效管理您的线上商城，提升运营效率与销售业绩</p>
          <div class="feature-list">
            <div class="feature-item">
              <el-icon><Star /></el-icon>
              <span>数据化运营分析</span>
            </div>
            <div class="feature-item">
              <el-icon><Goods /></el-icon>
              <span>全品类商品管理</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>客户关系维护</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单区 -->
      <div class="login-form-container">
        <div class="login-card">
          <div class="login-header">
            <h2 class="login-title">管理员登录</h2>
            <p class="login-subtitle">请输入账号信息登录管理系统</p>
          </div>

          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                :prefix-icon="User"
                :autofocus="true"
                class="custom-input"
              ></el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                :type="showPassword ? 'text' : 'password'"
                class="custom-input"
              >
                <template #suffix>
                  <el-icon
                    @click="showPassword = !showPassword"
                    class="password-toggle"
                  >
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>

            <div class="form-options">
              <el-checkbox v-model="rememberMe" size="small">记住密码</el-checkbox>
              <el-link type="primary" :underline="false" class="forgot-link">忘记密码?</el-link>
            </div>

            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleLogin"
              >
                登录系统
              </el-button>
            </el-form-item>
          </el-form>

          <div class="login-footer">
            <p>© 2025 LetaoMallManager</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router' // Vue Router 导航 hook
import { ElMessage } from 'element-plus' // 消息提示
import request from '@/utils/request' // 引入 Axios 实例
import { Star, Goods, User, Lock, ShoppingCart, View, Hide } from '@element-plus/icons-vue'
const showPassword = ref(false) // 密码可见状态（新增）

// 1. 表单相关：表单引用、表单数据、校验规则
const loginFormRef = ref(null) // 表单引用（用于验证）
const loginForm = reactive({ // 表单数据（与后端接收的参数名匹配）
  username: '', // 对应后端的 "username"
  password: '',  // 对应后端的 "password"
})

// 记住密码状态（新增）
const rememberMe = ref(false)
// 表单校验规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
})

// 2. 登录状态：加载中
const loading = ref(false)

// 3. 路由实例：用于登录成功后跳转
const router = useRouter()

// Cookie 操作工具函数（简单实现，使用 document.cookie）
const setCookie = (name, value, days) => {
  const expires = new Date()
  expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000))
  document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=/;SameSite=Strict`
}

const getCookie = (name) => {
  const nameEQ = name + '='
  const ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') c = c.substring(1, c.length)
    if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length))
  }
  return null
}

const removeCookie = (name) => {
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`
}

// 4. 页面加载时读取 Cookie 并填充表单（实现记住我功能）
onMounted(() => {
  const savedUsername = getCookie('remember_username')
  const savedPassword = getCookie('remember_password')
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword
    rememberMe.value = true
  }
})

// 5. 真实登录逻辑：对接后端接口
const handleLogin = async () => {
  try {
    // 步骤1：表单验证（通过则继续，不通过则触发校验提示）
    await loginFormRef.value.validate()

    // 步骤2：显示加载状态
    loading.value = true
    // 更新是否记住我（传递给后端，后端可据此调整 token 过期时间）
    loginForm.rememberMe = rememberMe.value;

    // 步骤3：发送 POST 请求到后端登录接口
    const response = await request({
      url: '/admin/login',
      method: 'POST',
      data: loginForm // 后端接收的 JSON 请求体 { username, password, rememberMe }
    })
    // 步骤4：根据后端返回的 JSON 数据判断登录结果
    if (response.success) {
      // 登录成功：
      // 1. 提示成功消息
      ElMessage.success(response.msg || '登录成功，正在进入系统...')
      
      // 2. 保存用户信息到 Pinia Store（核心权限数据存储）
      const { useUserStore } = await import('@/store/index.js')
      const userStore = useUserStore()
      userStore.setUserInfo(response)
      
      // 3. 记住我功能：如果选中，保存用户名和密码到 Cookie（过期时间 7 天）
      if (rememberMe.value) {
        setCookie('remember_username', loginForm.username, 7)
        setCookie('remember_password', loginForm.password, 7)
      } else {
        // 未选中，清除 Cookie
        removeCookie('remember_username')
        removeCookie('remember_password')
      }

      // 4. 记住我功能：如果选中，保存用户名和密码到 Cookie（过期时间 7 天）
      if (rememberMe.value) {
        setCookie('remember_username', loginForm.username, 7)
        setCookie('remember_password', loginForm.password, 7)
      } else {
        // 未选中，清除 Cookie
        removeCookie('remember_username')
        removeCookie('remember_password')
      }

      // 5. 跳转到主界面的仪表盘子路由（/main/dashboard）
      router.push({ name: 'dashboard' }) // 或用 path: '/main/dashboard'
    } else {
      // 登录失败（如用户名密码错误，后端返回 success: false）
      ElMessage.error(response.msg || '登录失败，请检查用户名和密码')
    }
  } catch (error) {
    // 异常处理：表单验证失败或请求异常（e.g., 网络/CORS/401）
    console.error('登录过程异常：', error); // 保留 console 用于调试
    ElMessage.error(error.response?.data?.msg || error.message || '登录异常，请重试');
    // 如果是 401 未授权，可额外清空 token（虽登录时少见）
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    }
  } finally {
    // 无论成功/失败，都关闭加载状态
    loading.value = false
  }
}
</script>

<style scoped>
/* 根元素字体大小动态调整，实现比例缩放 */
.login-page {
  font-size: clamp(14px, 1.5vw + 0.5rem, 16px); /* 基于视口宽度动态字体大小，便于缩放适应 */
  min-height: 100vh;
  background-color: #0a0a0a; /* 调整为深色背景以匹配参考图 */
  position: relative;
  overflow: hidden;
}

/* 动态流光背景：渐变动画 + 波浪层 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(315deg, rgba(101,0,94,1) 3%, rgba(60,132,206,1) 38%, rgba(48,238,226,1) 68%, rgb(128, 25, 255) 98%);
  animation: gradient 15s ease infinite;
  background-size: 400% 400%;
  background-attachment: fixed;
  z-index: 0;
}

@keyframes gradient {
  0% {
    background-position: 0% 0%;
  }
  50% {
    background-position: 100% 100%;
  }
  100% {
    background-position: 0% 0%;
  }
}

.wave {
  background: rgb(255 255 255 / 25%);
  border-radius: 1000% 1000% 0 0;
  position: absolute;
  width: 200%;
  height: 12em;
  animation: wave 10s -3s linear infinite;
  transform: translate3d(0, 0, 0);
  opacity: 0.8;
  bottom: 0;
  left: 0;
  z-index: -1;
}

.wave:nth-of-type(2) {
  bottom: -1.25em;
  animation: wave 18s linear reverse infinite;
  opacity: 0.8;
}

.wave:nth-of-type(3) {
  bottom: -2.5em;
  animation: wave 20s -1s reverse infinite;
  opacity: 0.9;
}

@keyframes wave {
  2% {
    transform: translateX(1);
  }

  25% {
    transform: translateX(-25%);
  }

  50% {
    transform: translateX(-50%);
  }

  75% {
    transform: translateX(-25%);
  }

  100% {
    transform: translateX(1);
  }
}

.login-container {
  display: flex;
  width: 100%;
  max-width: clamp(800px, 90vw, 1200px); /* 使用clamp动态最大宽度 */
  height: 100vh;
  margin: 0 auto;
  position: relative;
  z-index: 1;
  overflow: hidden; /* 防止容器溢出 */
}

/* 左侧品牌展示区 */
.login-banner {
  flex: clamp(1, 1.2, 1.5); /* 动态flex值 */
  background: linear-gradient(135deg, #2c3e50, #34495e);
  color: #fff;
  padding: clamp(1rem, 3vw, 2rem); /* 动态padding */
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
  min-height: 100vh; /* 确保最小高度 */
}

.login-banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
  background-size: 20%; /* 调整背景图案大小以适应缩放 */
}

.banner-content {
  max-width: clamp(300px, 40vw, 450px); /* 动态最大宽度 */
  margin-left: clamp(2rem, 5vw, 5rem);
  position: relative;
  z-index: 1;
  width: 100%; /* 确保宽度适应 */
}

.brand-logo {
  display: flex;
  align-items: center;
  margin-bottom: clamp(1.5rem, 4vw, 3rem);
}

.logo-icon {
  font-size: clamp(1.5rem, 4vw, 2.5rem); /* 动态图标大小 */
  margin-right: clamp(0.5rem, 1.5vw, 0.8rem);
  color: #4299e1;
}

.brand-name {
  font-size: clamp(1.5rem, 3vw, 2.2rem);
  font-weight: 700;
  margin: 0;
}

.banner-title {
  font-size: clamp(1.2rem, 2.5vw, 2rem);
  margin-bottom: clamp(0.5rem, 1.5vw, 1rem);
  font-weight: 600;
}

.banner-desc {
  font-size: clamp(0.9rem, 1.8vw, 1.1rem);
  opacity: 0.9;
  margin-bottom: clamp(2rem, 5vw, 3rem);
  line-height: 1.6;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: clamp(1rem, 2.5vw, 1.5rem);
}

.feature-item {
  display: flex;
  align-items: center;
  font-size: clamp(0.8rem, 1.5vw, 1rem);
  opacity: 0.9;
}

.feature-item el-icon {
  margin-right: clamp(0.5rem, 1.5vw, 0.8rem);
  font-size: clamp(0.8rem, 2vw, 1.2rem);
  color: #4299e1;
}

/* 右侧登录表单区 */
.login-form-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: clamp(1rem, 3vw, 2rem);
  min-height: 100vh; /* 确保最小高度 */
  overflow: auto; /* 允许滚动以防溢出 */
}

.login-card {
  width: 100%;
  max-width: clamp(300px, 35vw, 400px); /* 动态卡片宽度 */
  padding: clamp(1.5rem, 4vw, 2.5rem);
  background-color: #fff;
  border-radius: clamp(0.5rem, 2vw, 12px);
  box-shadow: 0 clamp(0.4rem, 1vw, 10px) clamp(0.8rem, 2vw, 30px) rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.login-header {
  text-align: center;
  margin-bottom: clamp(1rem, 3vw, 2rem);
}

.login-title {
  font-size: clamp(1.2rem, 2.5vw, 1.6rem);
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.login-subtitle {
  font-size: clamp(0.8rem, 1.5vw, 0.95rem);
  color: #64748b;
  margin: 0;
}

.login-form {
  width: 100%;
}

.custom-input {
  height: clamp(2.5rem, 6vw, 3.125rem); /* 动态输入框高度 */
  border-radius: clamp(0.3rem, 1vw, 0.5rem);
  border-color: #e2e8f0;
  transition: all 0.2s ease;
  font-size: inherit; /* 继承父级字体大小 */
}

.custom-input:focus-within {
  border-color: #4299e1;
  box-shadow: 0 0 0 clamp(0.1rem, 0.3vw, 0.1875rem) rgba(66, 153, 225, 0.1);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: clamp(0.5rem, 2vw, 1rem) 0 clamp(0.75rem, 2.5vw, 1.5rem);
  font-size: clamp(0.7rem, 1.5vw, 0.9rem);
}

.forgot-link {
  font-size: clamp(0.7rem, 1.5vw, 0.9rem);
  color: #4299e1;
}

.login-button {
  width: 100%;
  height: clamp(2.5rem, 6vw, 3.125rem);
  font-size: clamp(0.8rem, 1.8vw, 1rem);
  border-radius: clamp(0.3rem, 1vw, 0.5rem);
  background-color: #4299e1;
  border-color: #4299e1;
  transition: all 0.2s ease;
}

.login-button:hover {
  background-color: #3182ce;
  border-color: #3182ce;
  transform: translateY(-0.125rem);
}

.login-button:active {
  transform: translateY(0);
}

.login-footer {
  text-align: center;
  margin-top: clamp(1rem, 3vw, 2rem);
  font-size: clamp(0.6rem, 1.2vw, 0.85rem);
  color: #94a3b8;
}

.password-toggle {
  cursor: pointer;
  color: #94a3b8;
  transition: color 0.2s;
  font-size: inherit;
}

.password-toggle:hover {
  color: #4299e1;
}

/* 响应式设计 - 增强断点 */
@media (max-width: 992px) {
  .login-container {
    flex-direction: column;
    height: auto; /* 允许自适应高度 */
    min-height: 100vh;
  }

  .login-banner {
    flex: none;
    padding: clamp(1.5rem, 5vw, 3rem) clamp(1rem, 3vw, 2rem);
    text-align: center;
    min-height: auto; /* 移除固定高度，允许自适应 */
    height: auto;
  }

  .banner-content {
    margin: 0 auto;
    max-width: 90vw;
  }

  .brand-logo {
    justify-content: center;
  }

  .feature-list {
    align-items: center;
  }

  .login-form-container {
    padding: clamp(1.5rem, 5vw, 3rem) clamp(1rem, 3vw, 2rem);
    min-height: auto;
    height: auto;
  }
}

@media (max-width: 576px) {
  .login-card {
    padding: clamp(1rem, 4vw, 2rem) clamp(0.75rem, 2vw, 1.5rem);
    margin: 1rem; /* 添加边距防止边缘溢出 */
  }

  .banner-title {
    font-size: clamp(1rem, 2.5vw, 1.6rem);
  }

  .brand-name {
    font-size: clamp(1.2rem, 3vw, 1.8rem);
  }

  .login-container {
    padding: 0 0.5rem; /* 小屏添加侧边padding */
    overflow-x: hidden; /* 防止水平溢出 */
  }
}

/* 调试模式：可选，添加边框以便调试布局（生产环境可移除） */
:deep(.debug-mode .login-container > *),
:deep(.debug-mode .login-card),
:deep(.debug-mode .banner-content) {
  border: 1px solid rgba(255, 0, 0, 0.3); /* 半透明红色边框，便于查看元素边界 */
}

/* 要启用调试，在模板中添加 class="debug-mode" 到 .login-page */
</style>